import { conversationUpdate } from '@/services/workBench';
import { useStoreWorkbench } from '@/store/workbench';
import { Col, Form, Modal, Row, Select } from 'antd';
import { useEffect, useState } from 'react';

interface Iprops {
  visibleModal: boolean;
  relativeId: string;
  init: () => void;
}

const RelationModal: React.FC<Iprops> = ({
  visibleModal,
  relativeId,
  init,
}) => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { projectData } = useStoreWorkbench();
  const [projectList, setProjectList] = useState<any>([]);
  const [requireList, setRequireList] = useState<any>([]);

  useEffect(() => {
    if (projectData) {
      const arr = projectData.filter((item) => item?.id !== '未分类会话');
      setProjectList(
        arr.map((item) => ({ ...item, label: item?.name, value: item?.id })),
      );
    }
  }, [projectData]);

  useEffect(() => {
    if (visibleModal) {
      setVisible(true);
      form.resetFields();
    }
  }, [visibleModal]);

  const onClose = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleOk = () => {
    form
      .validateFields()
      .then(async (values: any) => {
        const param = {
          ...values,
        };
        param.id = relativeId;
        await conversationUpdate(param);
        document.dispatchEvent(new CustomEvent('emitSearch'));
        init();
        onClose();
        // Modal.confirm({
        //   title: '确认生成代码',
        //   content: '是否确定生成代码？',
        //   onOk() {
        //     setConfirmLoading(true);
        //     // 这里可以添加生成代码的逻辑
        //     // onGenerate(values);
        //     // setConfirmLoading(false);
        //     // onClose();
        //   },
        //   onCancel() {
        //     // 用户取消操作，不做任何事
        //   },
        // });
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };

  return (
    <Modal
      title="关联项目"
      open={visible}
      onOk={handleOk}
      onCancel={onClose}
      confirmLoading={confirmLoading}
      okText="保存"
    >
      <Form
        style={{ marginTop: 40 }}
        form={form}
        labelCol={{
          span: 6,
        }}
        initialValues={{
          projectId: '',
          requirementId: '',
        }}
      >
        <Row>
          <Col span={24}>
            <Form.Item
              label="关联项目"
              name="projectId"
              rules={[{ required: true, message: '不得为空' }]}
            >
              <Select
                placeholder="请选择"
                options={projectList || []}
                onChange={(value) => {
                  const flag = projectData.find((item) => item?.id === value);
                  if (flag) {
                    setRequireList(
                      flag.requirementList.map(
                        (item: { title: any; id: any }) => ({
                          ...item,
                          label: item?.title,
                          value: item?.id,
                        }),
                      ),
                    );
                  }
                }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Form.Item
              label="关联需求"
              name="requirementId"
              rules={[{ required: false, message: '不得为空' }]}
            >
              <Select allowClear placeholder="请选择" options={requireList} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default RelationModal;
